package com.atguigu.app.dwd;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.util.DateFormatUtil;
import com.atguigu.util.KafkaUtil;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.RichFilterFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * 监测误触
 * @Author ysp
 * @Date 2022/12/13 11:31
 */
// 数据流：web/app -> Nginx -> 日志服务器(.log) -> Flume -> Kafka(ODS) -> FlinkApp -> Kafka(DWD) -> FlinkApp -> Kafka(DWD)
// 程序:   Mock(lg.sh) -> Flume(f1) -> Kafka(ZK) -> BaseLogApp -> Kafka(ZK) -> DwdTrafficUniqueVisitor -> Kafka(ZK)
public class DwdTrafficUniqueVisitorDetail {

    public static void main(String[] args) throws Exception {
        // TODO 1. 获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        // 1.1 开启CheckPoint
//        env.enableCheckpointing(5 * 60000L, CheckpointingMode.EXACTLY_ONCE);
//        env.getCheckpointConfig().setCheckpointTimeout(60000L);
//        env.getCheckpointConfig().setMaxConcurrentCheckpoints(2);
//        env.setRestartStrategy(RestartStrategies.fixedDelayRestart(3, 5000L));
//
//        // 设置状态后端
//        env.setStateBackend(new HashMapStateBackend());
//        env.getCheckpointConfig().setCheckpointStorage("hdfs://192.168.60.202:8020/ck");
//        System.setProperty("HADOOP_USER", "atguigu");

        // TODO 2. 读取kafka页面日志主题创建流
        String topic = "dwd_traffic_page_log";
        String group = "dwd_traffic_user_jump_detail";
        DataStreamSource<String> kafkaDS = env.addSource(KafkaUtil.getFlinkKafkaConsumer(topic, group));

        // TODO 3. 过滤掉上一跳页面不为null的数据并将每行数据转换为JSON对象
        SingleOutputStreamOperator<JSONObject> jsonobjDS =
                kafkaDS.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String s, Collector<JSONObject> collector) throws Exception {
                try {
                    JSONObject jsonObject = JSON.parseObject(s);
                    String lastPage = jsonObject.getJSONObject("page").getString("last_page_id");
                    if (lastPage == null) {
                        collector.collect(jsonObject);
                    }

                } catch (Exception e) {
                    System.out.println("数据格式错误：" + s);
                }
            }
        });

        // TODO 4. 按照Mid分组
        KeyedStream<JSONObject, String> keyedStream = jsonobjDS.keyBy(json -> json.getJSONObject(
                "common").getString("mid"));
        // TODO 5. 使用状态编程实现按照Mid的去重
        SingleOutputStreamOperator<JSONObject> filterDS = keyedStream.filter(new RichFilterFunction<JSONObject>() {

            private ValueState<String> lastState;


            @Override
            public void open(Configuration parameters) throws Exception {
                ValueStateDescriptor<String> stateDescriptor = new ValueStateDescriptor<>("last_state", String.class);
                StateTtlConfig ttlConfig = new StateTtlConfig.Builder(Time.days(1))
                        .setUpdateType(StateTtlConfig.UpdateType.OnCreateAndWrite)
                        .build();
                stateDescriptor.enableTimeToLive(ttlConfig);
                lastState = getRuntimeContext().getState(stateDescriptor);

            }

            @Override
            public boolean filter(JSONObject jsonObject) throws Exception {
                // 获取状态时间&当前时间戳并转化为日期
                String lastDate = lastState.value();
                Long ts = jsonObject.getLong("ts");
                String curDate = DateFormatUtil.toDate(ts);

                if (lastDate == null || !lastDate.equals(curDate)) {
                    lastState.update(curDate);
                    return true;
                } else {
                    return false;
                }
            }
        });

        // TODO 6. 将数据写到Kafka
        String targetTopic = "traffic_unique_visitor_detail";
        filterDS.print(">>>>>>>>>");
        filterDS.map(jsonObject -> jsonObject.toJSONString())
                .addSink(KafkaUtil.getFlinkKafkaProducer(targetTopic));
        // TODO 7. 启动任务
        env.execute("dwd_traffic_user_jump_detail");
    }
}
